package com.ficus.road.maintain.controller;

import com.ficus.road.maintain.core.model.GpsHistory;
import com.ficus.road.maintain.core.model.GpsQueryRequestDTO;
import com.ficus.road.maintain.dao.GpsHistoryDao;
import com.ficus.road.maintain.service.GpsHistoryService;
import com.ficus.road.maintain.service.TheoryGpsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class GpsHistoryController {

    public static final int MAX_SIZE = 10000;
    @Autowired
    private GpsHistoryService gpsHistoryService;
    @Autowired
    private TheoryGpsService theoryGpsService;
    @Value("${hit-config.maxdistance}")
    private int maxdistance;

    //查询历史GPS列表
    @RequestMapping(value = "/historyGps/query",
            produces = {"application/json"},
            method = RequestMethod.POST)
//    @PreAuthorize("@rm.check('ROAD_NETWORK')")
    public ResponseEntity<List<GpsHistory>> queryHistoryGps(@Min(0) @Valid @RequestParam(defaultValue = "0") Integer start,
                                                            @Min(1) @Valid @RequestParam(defaultValue = "100000") Integer limit,
                                                            @Valid @RequestBody GpsQueryRequestDTO queryRequestDTO) {
        String carId = queryRequestDTO.getCarId();

        Long startTime = queryRequestDTO.getStartTime();
        Long endTime = queryRequestDTO.getEndTime();
        Criteria criteria = Criteria.where("timestamp");
        if (startTime != null) {
            criteria.gt(startTime);
        }
        if (endTime != null) {
            criteria.lte(endTime);
        } else {
            criteria.lte(System.currentTimeMillis() / 1000);
        }
        criteria.and("car_id").is(carId);
        Query query = Query.query(criteria);
        query.skip(start).limit(limit);
        List<GpsHistory> histories = gpsHistoryService.query(query);
        query.fields().include("_id");
        query.skip(0).limit(MAX_SIZE);
        List<GpsHistory> totalList = gpsHistoryService.query(query);
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        Boolean isFinal = Boolean.FALSE;
        if (limit != null) {
            if (histories.size() != limit) {
                isFinal = Boolean.TRUE;
            }
        }

        headers.add("X-OneAPI-Exhausted", String.valueOf(isFinal));
        headers.add("X-OneAPI-EstimatedSize", String.valueOf(totalList.size()));
        return new ResponseEntity<>(histories, headers, HttpStatus.OK);
    }

    @Autowired
    GpsHistoryDao gpsHistoryDao;

    public void init(){
        Criteria criteria = Criteria.where("creation_time").lt(new Date(1686498372L * 1000))
                .gt(new Date(1686426372L * 1000));
        criteria.and("car_id").is("YTKJ20210075");
        Query query = Query.query(criteria);
        List<GpsHistory> histories = gpsHistoryDao.findByQuery(query);
        for (GpsHistory history : histories) {
            gpsHistoryDao.update(history.getId(), Update.update("timestamp", history.getCreationTime().getTime()/1000));
        }
        System.out.println(1);
    }

    //查询分钟级别历史gps列表
    @RequestMapping(value = "/historyGps/minute/query",
            produces = {"application/json"},
            method = RequestMethod.POST)
//    @PreAuthorize("@rm.check('ROAD_NETWORK')")
    public ResponseEntity<List<GpsHistory>> queryHistoryGpsByMinute(@Min(0) @Valid @RequestParam(defaultValue = "0") Integer start,
                                                                    @Min(1) @Valid @RequestParam(defaultValue = "1000") Integer limit,
                                                                    @Valid @RequestBody GpsQueryRequestDTO queryRequestDTO) {
        String carId = queryRequestDTO.getCarId();
        Long startTime = queryRequestDTO.getStartTime();
        Long endTime = queryRequestDTO.getEndTime();
        Criteria criteria = Criteria.where("timestamp");
        if (startTime != null) {
            criteria.gt(startTime);
        }
        if (endTime != null) {
            criteria.lte(endTime);
        } else {
            criteria.lte(System.currentTimeMillis() / 1000);
        }
        criteria.and("car_id").is(carId);
        Query query = Query.query(criteria);
        query.skip(start).limit(limit);
        List<GpsHistory> histories = gpsHistoryService.queryMinute(query);
        query.fields().include("_id");
        query.skip(0).limit(MAX_SIZE);
        List<GpsHistory> totalList = gpsHistoryService.queryMinute(query);
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        Boolean isFinal = Boolean.FALSE;
        if (limit != null) {
            if (histories.size() != limit) {
                isFinal = Boolean.TRUE;
            }
        }

        headers.add("X-OneAPI-Exhausted", String.valueOf(isFinal));
        headers.add("X-OneAPI-EstimatedSize", String.valueOf(totalList.size()));
        return new ResponseEntity<>(histories, headers, HttpStatus.OK);
    }
//
//    @DeleteMapping("/gps/delete")
//    public ResponseEntity<List<String>> deleteGpsData() {
//
//
//        return null;
//    }

    @GetMapping("/gps/check/{carId}/{timestamp}")
    public ResponseEntity<String> checkBreakPoint(@PathVariable("carId") String carId, @PathVariable("timestamp") Long timestamp) {
        List<GpsHistory> histories = gpsHistoryService.findGpsByCarIdAndTimeStampGte(carId, timestamp);
        List<Long> list = histories.stream().map(GpsHistory::getTimestamp).collect(Collectors.toList());
        for (int i = 0; i < list.size() - 1; i++) {
            Long pre = list.get(i);
            Long post = list.get(i + 1);
            if (post - pre > 2) {
                System.out.println(pre);
                System.out.println(post);
            }
        }
        return new ResponseEntity<>("finish", HttpStatus.OK);
    }
}
